const mars3d = window.mars3d;
const Cesium = window.Cesium;

export const mapImageLayer = () => {
    const state = {
        map: null,
        layer: null,
    }
    const addLayer = async (map, options) => {
        // 动态加载图片元数据
        const img = new Image();
        img.src = options.url;
        await new Promise((resolve) => (img.onload = resolve));

        // 计算图片宽高比
        const aspectRatio = img.width / img.height;
        const center = options.center || {lng: 119.0315, lat: 33.5925};
        const latSpan = options.latSpan || 0.008;

        // 根据纬度调整经度跨度
        const lngSpan = latSpan * aspectRatio / Math.cos(Cesium.Math.toRadians(center.lat));

        // 创建图层
        state.map = map;
        state.layer = new mars3d.layer.ImageLayer({
            name: options.name,
            url: options.url,
            rectangle: Cesium.Rectangle.fromDegrees(
                center.lng - lngSpan / 2,
                center.lat - latSpan / 2,
                center.lng + lngSpan / 2,
                center.lat + latSpan / 2
            ),
        });
        state.map.addLayer(state.layer);
        return state.layer;
    }
    const removeLayer = (map) => {
        state.map = map;
        state.map.removeLayer(state.layer, true)
        state.layer = null;
    }
    return {
        addLayer,
        removeLayer
    }
}